import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Form, Row, Col, Input, Button, Table, message, DatePicker, Select, Space, Divider, Modal } from 'antd'
import { UpOutlined, DownOutlined, DownloadOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import moment from 'moment'
import { addWindow } from '@redux/actions'
import style from '@pages/filingCaseManage/CaseManage.module.less'
import CaseNoRender from '@components/CaseNoRender'
import { getEmployeeListRequest, getLeaderListRequest } from './ajax'
import { awaitWrap } from '@js/tool'
import { json2Excel } from '@js/excel'
import nStyle from './Index.module.less'
import SelectedModal from './components/SelectedModal/Index'
import StatusModal from './components/StatusModal/Index'
import Dictionary from '@js/dictionary'
import { download } from '@js/downloadRename'

const { Item } = Form
const { Option } = Select
const { confirm } = Modal

const layout = {
  labelCol: { flex: '100px' }
}

// 获取表格字段配置
function getColumns () {
  return [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'key',
      align: 'center',
      width: 60
    },
    {
      title: '案号',
      dataIndex: 'caseno_desc',
      key: 'caseno_desc',
      width: 200,
      render: (v, l) => {
        return <CaseNoRender data={l} />
      }
    },
    {
      title: '文档名称',
      dataIndex: 'document_name',
      key: 'document_name'
    },
    {
      title: '文书流水号',
      dataIndex: 'serialno_desc',
      key: 'serialno_desc'
    },
    {
      title: '经办秘书',
      dataIndex: 'creator',
      key: 'creator',
      width: 100
    },
    {
      title: '审批人',
      dataIndex: 'approver',
      key: 'approver',
      width: 100
    },
    {
      title: '审批状态',
      dataIndex: 'status',
      key: 'status',
      width: 100
    },
    {
      title: '审批时间',
      dataIndex: 'approve_datetime',
      key: 'approve_datetime',
      width: 120,
      render: v => {
        return v ? moment(v * 1000).format('YYYY-MM-DD') : ''
      }
    },
    {
      title: '操作',
      dataIndex: 'operate',
      key: 'operate',
      width: 120,
      render: (v, li) => {
        return (
          <Space split={<Divider type='vertical' />}>
            {li.approve_file && <a onClick={() => download(li.approve_file.path, li.approve_file.original_filename)}>查看文书</a>}
          </Space>
        )
      }
    }
  ]
}

class SimpleSearch extends Component {
  state = {
    searchToggleBtn: false,
    loading: false,
    list: [],
    employeeList: [],
    leaderList: [],
    condition: [],
    selectedRowKeys: [],
    selectedRows: [],
    statusList: [],
    visible: false,
    statusVisible: false,
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条记录`,
      size: 'small'
    }
  }

  formRef = React.createRef()

  // 改变案件状态
  changeStatus (status) {
    this.setState({
      status,
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  // 获取案件数据
  getTableData (form) {
    form = form || this.formRef.current.getFieldsValue()
    const { pagination } = this.state
    const { current, pageSize } = pagination
    const condition = []
    this.setState({ loading: true })
    if (form.creatorid) {
      condition.push({ k: 'creatorid', o: '=', v: form.creatorid })
    }
    if (form.approverid) {
      condition.push({ k: 'approverid', o: '=', v: form.approverid })
    }
    if (form.caseno_desc) {
      condition.push({ k: 'caseno_desc', o: 'like', v: `%${form.caseno_desc}%` })
    }
    if (form.document_name) {
      condition.push({ k: 'document_name', o: 'like', v: `%${form.document_name}%` })
    }
    if (form.beginTime) {
      condition.push({ k: 'approve_datetime', o: '>=', v: Math.floor(moment(form.beginTime.format('YYYY-MM-DD')).valueOf() / 1000) })
    }
    if (form.endTime) {
      condition.push({ k: 'approve_datetime', o: '<=', v: Math.floor(moment(form.endTime.format('YYYY-MM-DD') + ' 23:59:59').valueOf() / 1000) })
    }
    if (form.status && form.status.length > 0) {
      condition.push({ k: 'status', o: 'in', v: form.status.join() })
    }
    this.setState({
      condition
    })
    delete form.beginTime
    delete form.endTime
    this.$get('/api/xapc/docapprove', {
      current,
      page_size: pageSize,
      condition: JSON.stringify(condition)
    }).then(res => {
      this.setState({ loading: false })
      if (res.status === 1) {
        this.setState({
          list: res.data.list.map((li, i) => {
            li.key = pageSize * (current - 1) + i + 1
            return li
          }),
          pagination: {
            ...pagination,
            total: res.data.total
          }
        })
      } else {
        return message.warning(res.message)
      }
    }).catch(() => this.setState({ loading: false }))
  }

  // 表格请求变化
  tableChange ({ current, pageSize }) {
    this.setState({
      pagination: {
        ...this.state.pagination,
        current,
        pageSize
      }
    }, () => {
      this.getTableData()
    })
  }

  // 重置表格
  resetHandle () {
    this.formRef.current.resetFields()
    this.setState({
      condition: [],
      selectedRowKeys: [],
      selectedRows: []
    })
    this.setState({
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  initFormByMeta () {
    const c = this.formRef.current
    const { formData = {} } = this.props.meta || {}
    c.resetFields()
    c.setFieldsValue(formData)
    c.submit()
  }

  async initEmpolyeeList () {
    const [e, d] = await awaitWrap(getEmployeeListRequest())
    if (e === null && d !== null) {
      this.setState({ employeeList: d })
    }
  }

  async initLeaderList () {
    const [e, d] = await awaitWrap(getLeaderListRequest())
    if (e === null && d !== null) {
      this.setState({ leaderList: d })
    }
  }

  // 二次弹框确认下载excel
  confirmDownload () {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: '您确定要导出excel吗？',
      onOk: () => {
        this.downloadExcel()
      }
    })
  }

  // 获取当前查询条件的全部数据，并下载excel
  downloadExcel () {
    const current = 1
    const pageSize = 1000000
    const hide = message.loading('导出中', 300)
    this.$get('/api/xapc/docapprove', {
      current,
      page_size: pageSize,
      condition: JSON.stringify(this.state.condition)
    }).then(res => {
      hide()
      if (res.status === 1) {
        const list = res.data.list.map((l, i) => {
          const date = l.approve_datetime ? moment(l.approve_datetime * 1000).format('YYYY-MM-DD') : ''
          return {
            序号: pageSize * (current - 1) + i + 1,
            案号: l.caseno_desc,
            文档名称: l.document_name,
            文书流水号: l.serialno_desc,
            经办秘书: l.creator,
            审批人: l.approver,
            审批状态: l.status,
            审批时间: date ? moment(date).toDate() : ''
          }
        })
        json2Excel([{ data: list, sheetname: '盖章呈批列表' }], '盖章呈批列表')
      } else {
        return message.warning(res.message)
      }
    }).catch(() => hide())
  }

  changeCreator (v) {
    const list = this.state.employeeList
    for (let i = 0; i < list.length; i++) {
      if (list[i].name === v) {
        this.formRef.current.setFieldsValue({ creatorid: list[i].id })
        break
      }
    }
  }

  changeApprover (v) {
    const list = this.state.leaderList
    for (let i = 0; i < list.length; i++) {
      if (list[i].name === v) {
        this.formRef.current.setFieldsValue({ approverid: list[i].id })
        break
      }
    }
  }

  componentDidUpdate (prev) {
    if (prev.meta !== this.props.meta) {
      this.initFormByMeta()
    }
  }

  componentDidMount () {
    this.initFormByMeta()
    this.initEmpolyeeList()
    this.initLeaderList()
    const d = new Dictionary()
    d.init('文书审批状态')
      .then(res => {
        this.setState({
          statusList: d.getList('文书审批状态')
        })
      })
      .catch(e => {
        console.error(e)
      })
  }

  // 渲染搜索表单的展开和收起
  renderToggleBtns () {
    if (this.state.searchToggleBtn) {
      return (
        <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
          <span>展开</span>
          <UpOutlined />
        </Button>
      )
    }
    return (
      <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
        <span>收起</span>
        <DownOutlined />
      </Button>
    )
  }

  render () {
    const columns = getColumns.call(this)
    const rowSelection = {
      selectedRowKeys: this.state.selectedRowKeys,
      preserveSelectedRowKeys: true,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          selectedRows,
          selectedRowKeys
        })
      }
    }
    const onRow = record => {
      return {
        onClick: event => {
          const s = [...this.state.selectedRowKeys]
          const sr = [...this.state.selectedRows]
          const i = s.indexOf(record.id)
          if (i !== -1) {
            s.splice(i, 1)
            sr.splice(i, 1)
          } else {
            s.push(record.id)
            sr.push(record)
          }
          this.setState({
            selectedRowKeys: s,
            selectedRows: sr
          })
        }
      }
    }
    return (
      <div className={style.container}>
        <SelectedModal visible={this.state.visible} data={this.state.selectedRows} hide={() => this.setState({ visible: false })} onChange={(l) => this.setState({ selectedRowKeys: l.map(l => l.id), selectedRows: l })} />
        <StatusModal visible={this.state.statusVisible} hide={() => this.setState({ statusVisible: false })} data={this.state.selectedRowKeys} refreshData={() => { this.tableChange(this.state.pagination); this.setState({ selectedRowKeys: [], selectedRows: [] }) }} statusList={this.state.statusList} />
        <div className={style['title-line']}>
          <span>{this.props.title}</span>
        </div>
        <div className={style['search-container']}>
          <div className={style['search-form']}>
            <Form
              name='doc_seal_list' {...layout} ref={this.formRef} onFinish={v => {
                this.setState({
                  selectedRowKeys: [],
                  selectedRows: []
                })
                this.getTableData(v)
              }}
            >
              <Row gutter={24}>
                <Col span={8}>
                  <Item label='案号' name='caseno_desc'>
                    <Input placeholder='请输入案号' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item name='creatorid' noStyle><span /></Item>
                  <Item label='经办秘书' name='creator'>
                    <Select placeholder='请选择' allowClear showSearch onChange={(v) => this.changeCreator(v)}>
                      {this.state.employeeList.map((li, i) => {
                        return (
                          <Option key={i} value={li.name}>{li.name}</Option>
                        )
                      })}
                    </Select>
                  </Item>
                </Col>
                <Col span={8}>
                  <Item name='approverid' noStyle><span /></Item>
                  <Item label='审批人' name='approver'>
                    <Select placeholder='请选择' allowClear showSearch onChange={(v) => this.changeApprover(v)}>
                      {this.state.leaderList.map((li, i) => {
                        return (
                          <Option key={i} value={li.name}>{li.name}</Option>
                        )
                      })}
                    </Select>
                  </Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col span={8}>
                  <Item label='审批起始日期' name='beginTime'>
                    <DatePicker className={style.full} placeholder='请选择日期' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='审批结束日期' name='endTime'>
                    <DatePicker className={style.full} placeholder='请选择日期' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='文档名称' name='document_name'>
                    <Input placeholder='请输入案号' />
                  </Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col span={8}>
                  <Item label='审批状态' name='status'>
                    <Select placeholder='请选择' allowClear showSearch mode='multiple'>
                      {this.state.statusList.map((li, i) => {
                        return (
                          <Option key={i} value={li.value}>{li.title}</Option>
                        )
                      })}
                    </Select>
                  </Item>
                </Col>
                <Col span={16}>
                  <Item>
                    <div className={style['search-btns']}>
                      <Button type='primary' ghost htmlType='submit'>搜索</Button>
                      <Button htmlType='reset' onClick={() => this.resetHandle()}>重置
                      </Button>
                      {/* {this.renderToggleBtns()} */}
                    </div>
                  </Item>
                </Col>
              </Row>
            </Form>
          </div>
        </div>
        <div className={style['download-btn-line']} style={{ marginBottom: '12px' }}>
          <Button type='primary' ghost onClick={() => this.confirmDownload()} icon={<DownloadOutlined />}>导出excel</Button>
        </div>
        <div className={style['table-container']}>
          <Table
            rowSelection={{ ...rowSelection }} selections={this.state.selectedRows} loading={this.state.loading} columns={columns} dataSource={this.state.list} pagination={this.state.pagination} onChange={v => this.tableChange(v)} onRow={onRow} rowKey={record => record.id}
          />
        </div>
        {
          this.state.selectedRowKeys.length > 0 && (
            <div className={nStyle.container}>
              <span className={nStyle['select-text']}>
                已选择
                <span className={nStyle['select-num']} onClick={() => this.setState({ visible: true })}>{this.state.selectedRows.length}</span>
                项
              </span>
              <Button type='primary' onClick={() => this.setState({ statusVisible: true })}>批量修改状态</Button>
            </div>
          )
        }
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    addWindow: (i) => dispatch(addWindow(i))
  }
})

export default connect(mapState, mapDispatch)(SimpleSearch)
